<template>
  <default-layout>
    <header-back text="修改头像" slot="header"></header-back>
    <div class="avatar scroll-view" slot="main">
      <div class="img-box">
        <img src="./avatar.jpg" id="faceId">
      </div>
    </div>
    <div class="edit" slot="footer">
      <div class="btn">
        <mt-button size="large" type="primary" plain @click="choose">选择图片</mt-button>
      </div>
      <div class="btn">
        <mt-button size="large" type="primary">保存</mt-button>
      </div>
    </div>
    <input type="file" ref="file" style="width: 0; height: 0; opacity: 0;" @change="handleImg($event)">
  </default-layout>
</template>
<script>
  import Cropper from 'cropperjs'
  import 'cropperjs/dist/cropper.css'
  import {http} from '../../common/js/util'
  import HeaderBack from '../../components/header-back/header-back.vue'
  import DefaultLayout from '../../layouts/default-layout/default-layout'

  export default {
    components: {DefaultLayout, HeaderBack},
    data() {
      return {
        loading: false,
        defaultImg: ''
      }
    },
    methods: {
      renderCropper() {
        const options = {
          aspectRatio: 1,
          minCropBoxWidth: 100,
          movable: false // 是否能拖动图片
        }
        this.crop = new Cropper(document.getElementById('faceId'), options)
      },
      doUpload() {
        if (!this.crop) return
        this.crop.getCroppedCanvas({
          width: 400,
          height: 400
        }).toBlob(blob => {
          const form = new FormData()
          form.append('file', blob)
          this.uploadToServer(form)
        })
      },
      uploadToServer(form) {
        if (this.loading) return
        http({
          method: 'post',
          url: '/api/users/face',
          form,
          headers: {
            'Content-Type': 'multipart/form-data;'
          }
        }, boo => {
          this.loading = boo
        }).then(res => {
        })
      },
      handleImg(e) {
        const file = e.target.files[0]
        if (file && this.crop) {
          if (this.tempImg) {
            URL.revokeObjectURL(this.tempImg)
          }
          this.tempImg = URL.createObjectURL(file)
          this.crop.replace(this.tempImg)
        }
      },
      choose() {
        this.$refs.file.click()
      }
    },
    mounted() {
      this.renderCropper()
    }
  }
</script>
<style lang="scss" scoped>
  @import "../../common/style/variable";

  .avatar {
    display: flex;
    justify-content: center;
    align-items: center;
    overflow-x: hidden;
    .img-box {
      width: 90%;
      img {
        width: 100%;
        display: block;
      }
    }
  }
  .edit {
    display: flex;
    justify-content: space-around;
    align-items: center;
    background: #fff;
    .btn {
      padding: 0 .2rem;
      flex: 1;
    }
  }
</style>
